package com.itheima.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/loginStudentServlet")
public class LoginStudentSever extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
       //获取用户名和密码
        String username = request.getParameter("username");
        String password = request.getParameter("password");


        //判断是否为空或者为空字符串(目前只判断名字没有固定值)
        if ( username.equals("panghu") &&  password.equals("123")) {
            //如果正确将用户名存入Session中
            request.getSession().setAttribute("username",username);

            String rem = request.getParameter("rem");
           if (rem != null) {
                request.getSession().setAttribute("username",username);
                request.getSession().setAttribute("password",password);
                Cookie cookie = new Cookie("username",username);
                Cookie cookie2 = new Cookie("password",password);
                cookie.setMaxAge(100000);
                cookie2.setMaxAge(100000);
                response.addCookie(cookie);
                response.addCookie(cookie2);

            }else{
               Cookie cookie = new Cookie("username","");
               Cookie cookie2 = new Cookie("password","");
               cookie.setMaxAge(0);
               cookie2.setMaxAge(0);
               response.addCookie(cookie);
               response.addCookie(cookie2);
           }

            //定向到index.jsp页面
            response.sendRedirect(request.getContextPath() + "/index.jsp");
            return;

        }else {
            //错误给出提示信息
            request.setAttribute("msg","用户名或密码错误");
            String msg = request.getParameter("msg");


            Cookie cookie = new Cookie("username","");
            Cookie cookie2 = new Cookie("password","");
            cookie.setMaxAge(0);
            cookie2.setMaxAge(0);

            response.addCookie(cookie);
            response.addCookie(cookie2);
            System.out.println(cookie.getName());

            //重定向到登录页面
            response.sendRedirect(request.getContextPath()+"/login.jsp");
            //request.getRequestDispatcher("/login.jsp").forward(request,response);
            return;

        }

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
